﻿using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Entities.BPM_Process;
using NP.BPMReportPlatform.FlowManagement;
using NP.BPMReportPlatform.FlowManagement.Dto;
using NP.BPMReportPlatform.HR;
using NP.BPMReportPlatform.HR.Dto;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NP.BPMReportPlatform.RecurringJobs.Dto.FlowManager;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    /// <summary>
    /// 手机费额度
    /// </summary>
    public class PhoneFeeLimitRecurringJob : BpmReportPlatformRecurringJob, IPhoneFeeLimitRecurringJob
    {
        private readonly SqlSugarClient _dbBusiness, _dbEngine, _dbPlatform, _dbProcess;
        private readonly IHRAppService _hRAppService;
        public PhoneFeeLimitRecurringJob(ISqlSugarAppService sqlSugarAppService, IConfiguration configuration, IHRAppService hRAppService)
        {
            _dbBusiness = sqlSugarAppService.GetBusinessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _hRAppService = hRAppService;
        }
        #region 手机费额度
        /// <summary>
        /// 自动更新手机费额度
        /// </summary>
        public async Task AutoPhoneFeeLimitAsync()
        {
            // 清理话费额度表中所有数据
            await _dbBusiness.Deleteable<PhoneFeeLimit>().ExecuteCommandAsync();
            //获取最新的话额度
            var list = await AutoUpdatePhoneFeeLimit();
            foreach (var item in list)
            {
                item.Id = Guid.NewGuid().ToString();
            }
            await _dbBusiness.Insertable<PhoneFeeLimit>(list).ExecuteCommandAsync();
        }

        private async Task<List<PhoneFeeLimit>> AutoUpdatePhoneFeeLimit()
        {
            List<PhoneFeeLimit> phoneFeeLimits = new List<PhoneFeeLimit>();

            //获取立邦所有用户
            var users = await _dbPlatform.Queryable<Users, UserExtension>((a, b) => a.WorkNumber == b.Sapemployeeid)
               .Where((a, b) => a.Status == 1 && b.Status == "3")
               .Select((a, b) => new UserExtensionDto()
               {
                   Sapemployeeid = b.Sapemployeeid,
                   Dutyname = b.Dutyname,
                   Employeepostname = b.Employeepostname,
                   Sapcompanycode = b.Sapcompanycode,
                   Poste = b.Poste,
                   Posnc = b.Posnc
               }).Distinct().ToListAsync();
            var now = DateTime.Now;
            //查询手机费额度配置信息
            var phoneFeeLimitConfigData = await _dbBusiness.Queryable<PhoneFeeLimitConfig>()
                .Where(x => Convert.ToDateTime(x.ExpiryDateStart) < now && Convert.ToDateTime(x.ExpiryDateEnd) > now)
                .ToListAsync();
            foreach (var item in users)
            {
                PhoneFeeLimit phoneFeeLimit = new PhoneFeeLimit();
                phoneFeeLimit.WorkNumber = item.Sapemployeeid;
                // 直接销售属于销售类，其它属于职能类
                if (item.Dutyname == "直接销售")
                {
                    var limit = phoneFeeLimitConfigData.Find(x => x.Type == "销售类" && x.Rank == item.Posnc)?.Limit;
                    phoneFeeLimit.Limit = limit.IsNullOrEmpty() ? "0" : limit;
                }
                else
                {
                    if (item.Posnc == "O12")
                    {
                        var limit = phoneFeeLimitConfigData.Find(x => x.Type == "职能类" && x.Rank == item.Posnc && x.RankName == item.Employeepostname)?.Limit;
                        phoneFeeLimit.Limit = limit.IsNullOrEmpty() ? "0" : limit;
                    }
                    else
                    {
                        var limit = phoneFeeLimitConfigData.Find(x => x.Type == "职能类" && x.Rank == item.Posnc)?.Limit;
                        phoneFeeLimit.Limit = limit.IsNullOrEmpty() ? "0" : limit;
                    }
                }
                var specialLimit = SpecialUserLimit(phoneFeeLimitConfigData, item);
                if (!specialLimit.IsNullOrEmpty())
                {
                    phoneFeeLimit.Limit = specialLimit;
                }
                phoneFeeLimits.Add(phoneFeeLimit);
            }
            return phoneFeeLimits;
        }
        private string SpecialUserLimit(List<PhoneFeeLimitConfig> phoneFeeLimitConfigData, UserExtensionDto userExtension)
        {
            string limit = null;
            var companycodeList = phoneFeeLimitConfigData.Where(x => x.Type == "公司").Select(x => x.Rank).ToList();
            if (SqlFunc.ContainsArray<string>(companycodeList.ToArray(), userExtension.Sapcompanycode))
            {
                limit = "0";
            }
            var specialUser = phoneFeeLimitConfigData.Find(x => x.Type == "特殊设置" && x.Rank == userExtension.Sapemployeeid);
            if (specialUser != null)
            {
                limit = specialUser.Limit;
            }
            return limit;
        }
        #endregion

        #region 交通费额度

        /// <summary>
        ///定时推送交通费额度到费控
        /// </summary>
        /// <returns></returns>
        public async Task PushTrafficFeeLimitAsync()
        {
            int batchSize = 200;
            var datas = await _dbBusiness.Queryable<TrafficFeeLimit>().ToListAsync();
            var mapperInput = datas.Select(x => new TrafficFeePushDataDto()
            {
                employee_number = x.WorkNumber,
                budget_amount = x.Limit,
                fiscal_date = x.FiscalDate
            }).OrderBy(x=>x.employee_number).ToList();
            for (int i = 0; i < mapperInput.Count; i += batchSize)
            {
                int remaining = mapperInput.Count - i;
                int currentBatchSize = Math.Min(remaining, batchSize);
                var batchs = mapperInput.Skip(i).Take(currentBatchSize).ToList();
                await _hRAppService.SyncTrafficFee(batchs);
            }
        }

        /// <summary>
        /// 自动更新交通费额度
        /// </summary>
        public async Task AutoTrafficFeeLimitAsync()
        {
            // 清理话费额度表中所有数据
            await _dbBusiness.Deleteable<TrafficFeeLimit>().ExecuteCommandAsync();
            //获取最新的话额度
            var list = await AutoUpdateTrafficFeeLimit();
            var fiscalDate = DateTime.Now.ToString("yyyy-MM");
            foreach (var item in list)
            {
                item.Id = Guid.NewGuid().ToString();
                item.FiscalDate = fiscalDate;
            }
            await _dbBusiness.Insertable<TrafficFeeLimit>(list).ExecuteCommandAsync();
        }

        private async Task<List<TrafficFeeLimit>> AutoUpdateTrafficFeeLimit()
        {
            List<TrafficFeeLimit> trafficFeeLimits = new List<TrafficFeeLimit>();

            //获取立邦所有用户
            var users = await _dbPlatform.Queryable<Users, UserExtension>((a, b) => a.WorkNumber == b.Sapemployeeid)
               .Where((a, b) => a.Status == 1 && b.Status == "3")
               .Select((a, b) => new UserExtDto()
               {
                   Sapemployeeid = b.Sapemployeeid,
                   FullPathText= a.FullPathText,
                   FullPathCode = a.FullPathCode,
                   Duty =b.Duty,
                   Dutyname = b.Dutyname,
                   Poste = b.Poste,
                   Posnc = b.Posnc
               }).Distinct().ToListAsync();
            var now = DateTime.Now;
            //查询交通费额度配置信息
            var trafficFeeLimitConfigData = await _dbBusiness.Queryable<TrafficFeeLimitConfig>()
                .Where(x => Convert.ToDateTime(x.ExpiryDateStart) < now && Convert.ToDateTime(x.ExpiryDateEnd) > now)
                .ToListAsync();
            var trafficFeeLimitConfigData1 = trafficFeeLimitConfigData.Where(x => x.Type == "工号");
            var trafficFeeLimitConfigData2 = trafficFeeLimitConfigData.Where(x => x.Type == "标准逻辑");
      
            foreach (var item in users)
            {
                TrafficFeeLimit trafficFeeLimit = new TrafficFeeLimit();
                trafficFeeLimit.WorkNumber = item.Sapemployeeid;
                // 优先级：工号>标准岗位>标准逻辑
                if (trafficFeeLimitConfigData1.Where(x => x.Category1 == item.Sapemployeeid).Count() > 0)
                { 
                    //按照特殊工号
                    var currnetConfig = trafficFeeLimitConfigData1.Where(x => x.Category1 == item.Sapemployeeid).FirstOrDefault();
                    trafficFeeLimit.Limit = currnetConfig.Limit;
                }
                else if (!string.IsNullOrEmpty(item.Duty) && trafficFeeLimitConfigData2.Where(x => item.FullPathCode.Contains(x.Category1)).Where(x => x.Category4.IsNullOrEmpty() ? false : item.Duty == x.Category4).Count() > 0)
                {
                    //按照标准岗位
                    var currnetConfig = trafficFeeLimitConfigData2.Where(x => item.FullPathCode.Contains(x.Category1)).Where(x => item.Duty==x.Category4).FirstOrDefault();
                    trafficFeeLimit.Limit = currnetConfig.Limit;
                }
                else if (trafficFeeLimitConfigData2.Where(x => item.FullPathCode.Contains(x.Category1))
                    .Where(x=>x.Category2.IsNullOrEmpty()?true:x.Category2==item.Posnc?.Substring(0, 1))
                     .Where(x => x.Category3.IsNullOrEmpty() ? true : x.Category3 == item.Dutyname)
                    .Where(x => x.Category4.IsNullOrEmpty() ? true : item.Duty == x.Category4)
                     .Count() > 0)
                {
                    //按照标准逻辑
                    var currnetConfig = trafficFeeLimitConfigData2.Where(x => item.FullPathCode.Contains(x.Category1))
                        .Where(x => x.Category2.IsNullOrEmpty() ? true : x.Category2 == item.Posnc.Substring(0, 1))
                        .Where(x => x.Category3.IsNullOrEmpty() ? true : x.Category3 == item.Dutyname)
                        .Where(x => x.Category4.IsNullOrEmpty() ? true : item.Duty == x.Category4).FirstOrDefault();
                    trafficFeeLimit.Limit = currnetConfig.Limit;
                }
                else
                {
                    trafficFeeLimit.Limit = "9999";
                }
                trafficFeeLimits.Add(trafficFeeLimit);
            }

            return trafficFeeLimits;
        }
        #endregion
    }
}
